<template>
  <div class="app-container">
    <!--用户数据-->
    <el-form ref="queryForm" size="small" :inline="true" v-show="showSearch" label-width="68px">
      <el-form-item label="文件名" prop="userName">
        <el-input

          placeholder="请输入文件名"
          clearable
          style="width: 240px"
          @keyup.enter.native="handleQuery"
        />
      </el-form-item>
      <el-form-item label="创建时间">
        <el-date-picker
          style="width: 240px"
          value-format="yyyy-MM-dd"
          type="daterange"
          range-separator="-"
          start-placeholder="开始日期"
          end-placeholder="结束日期"
        ></el-date-picker>
      </el-form-item>
      <el-form-item>
        <el-button type="primary" icon="el-icon-search" size="mini" @click="handleQuery">搜索</el-button>
        <el-button icon="el-icon-refresh" size="mini" @click="resetQuery">重置</el-button>
      </el-form-item>
    </el-form>

    <el-row :gutter="10" class="mb8">
      <el-col :span="1.5">
        <el-button
          type="danger"
          plain
          icon="el-icon-delete"
          size="mini"
          :disabled="multiple"
          @click="handleDelete"
        >删除
        </el-button>
      </el-col>
      <el-col :span="1.5">
        <el-button
          type="info"
          plain
          icon="el-icon-upload2"
          size="mini"
          @click="handleImport"
        >上传
        </el-button>
      </el-col>
      <el-col :span="1.5">
        <el-button
          type="warning"
          plain
          icon="el-icon-data-analysis"
          size="mini"
          :disabled="multiple"
          @click="batchFilt()"
        >批量筛选
        </el-button>
        <el-button
          type="primary"
          plain
          icon="el-icon-download"
          size="mini"
          @click="download()"
        >导出筛选结果
        </el-button>
      </el-col>
      <right-toolbar :showSearch.sync="showSearch" @queryTable="getList" :columns="columns"></right-toolbar>
    </el-row>

    <el-table v-loading="loading" :data="fileInfoList" @selection-change="handleSelectionChange">
      <el-table-column type="selection" width="50" align="center"/>
      <el-table-column type="index" label="序号" align="center" width="50"></el-table-column>
      <el-table-column label="文件名" align="center" key="originName" prop="originName" v-if="columns[0].visible"/>
      <el-table-column label="文件大小" align="center" key="size" prop="size" v-if="columns[1].visible"
                       :show-overflow-tooltip="true"
      />
      <el-table-column label="是否已筛选" align="center" key="isFilted" prop="isFilted" v-if="columns[2].visible">
        <template slot-scope="scope">
          <el-tag
            :type="scope.row.isFilted === '0' ? 'info' : scope.row.isFilted=== '1' ?'success':''"
            disable-transitions>{{scope.row.isFilted=== '0' ? '未筛选' : scope.row.isFilted=== '1' ?'已筛选':'正在筛选' }}</el-tag>
        </template>
      </el-table-column>

      <el-table-column label="创建时间" align="center" prop="createTime" v-if="columns[3].visible" width="160">
        <template slot-scope="scope">
          <span>{{ parseTime(scope.row.createTime) }}</span>
        </template>
      </el-table-column>
      <el-table-column
        label="操作"
        align="center"
        width="160"
        class-name="small-padding fixed-width"
      >
        <template slot-scope="scope" v-if="scope.row.id !== 1">
          <el-button
            size="mini"
            type="text"
            icon="el-icon-shopping-cart-1"
            @click="fileFilt()"
          >筛选
          </el-button>
          <el-button
            size="mini"
            type="text"
            icon="el-icon-delete"
            @click="handleDelete(scope.row)"
          >删除
          </el-button>
        </template>
      </el-table-column>
    </el-table>

    <pagination
      v-show="total>0"
      :total="total"
      :page.sync="queryParams.pageNum"
      :limit.sync="queryParams.pageSize"
      @pagination="getList"
    />

    <!-- 用户导入对话框 -->
    <el-dialog :title="upload.title" :visible.sync="upload.open" width="400px" :closeOnClickModal=false append-to-body>
      <el-upload
        ref="upload"
        accept=".xlsx, .xls"
        multiple
        :limit=50
        :headers="upload.headers"
        :action="upload.url + '?updateSupport=' + upload.updateSupport"
        :disabled="upload.isUploading"
        :on-change="handleFileChange"
        :on-progress="handleFileUploadProgress"
        :on-error="handleUploadError"
        :on-success="handleFileSuccess"
        :auto-upload="false"
        drag
      >
        <i class="el-icon-upload"></i>
        <div class="el-upload__text">将文件拖到此处，或<em>点击上传</em></div>
        <div class="el-upload__tip text-center" slot="tip">
          <span>仅允许导入xls、xlsx格式文件。</span>
<!--          <el-link type="primary" :underline="false" style="font-size:12px;vertical-align: baseline;"-->
<!--                   @click="importTemplate"-->
<!--          >下载模板-->
<!--          </el-link>-->
        </div>
      </el-upload>
      <div slot="footer" class="dialog-footer">
        <el-button type="primary" @click="submitFileForm">确 定</el-button>
        <el-button @click="upload.open = false">取 消</el-button>
      </div>
    </el-dialog>

<!--    批量筛选对话框-->
    <el-dialog :title="filter.title" :visible.sync="filter.open" width="400px" :closeOnClickModal=false  append-to-body>
      <el-form :model="dynamicValidateForm" ref="dynamicValidateForm" label-width="100px" class="demo-dynamic">
        <el-form-item
          v-for="(domain, index) in dynamicValidateForm.domains"
          :label="'渠道编码' + index"
          :key="domain.key"
          :prop="'domains.' + index + '.value'"
          :rules="{
      required: true, message: '渠道编码不能为空', trigger: 'blur'
    }"
        >
          <el-col :span="14"><el-input v-model="domain.value"></el-input></el-col>
          <el-col :span="8">  <el-button class="el-icon-minus" @click.prevent="removeDomain(domain)" circle></el-button></el-col>
        </el-form-item>
        <el-form-item label-width="252px">
          <el-col :span="8"><el-button @click="addDomain" icon="el-icon-plus" circle></el-button></el-col>
        </el-form-item>
        <el-form-item>
          <el-button type="primary" @click="fileFilt()">提交</el-button>
          <el-button @click="filter.open = false">重置</el-button>
        </el-form-item>
      </el-form>
<!--      <div slot="footer" class="dialog-footer">-->
<!--        <el-button type="primary" @click="fileFilt()">确 定</el-button>-->
<!--        <el-button @click="filter.open = false">取 消</el-button>-->
<!--      </div>-->
    </el-dialog>
  </div>
</template>

<script>
import { getToken } from '@/utils/auth'
import { saveAs } from 'file-saver'
import errorCode from '@/utils/errorCode'
import { getFileInfoList, filter, delInfo, downLoadFile } from '../../../api/excel/info'
import { blobValidate } from "@/utils/ruoyi";
import { Message } from 'element-ui'


export default {
  name: 'User',

  data() {
    return {
      // 遮罩层
      loading: true,
      // 选中数组
      ids: [],
      // 非单个禁用
      single: true,
      // 非多个禁用
      multiple: true,
      // 显示搜索条件
      showSearch: true,
      // 总条数
      total: 0,
      // 用户表格数据
      userList: null,
      // 弹出层标题
      title: '',
      // 部门树选项
      deptOptions: undefined,
      // 是否显示弹出层
      open: false,
      // 部门名称
      deptName: undefined,
      // 默认密码
      initPassword: undefined,
      // 日期范围
      dateRange: [],
      // 岗位选项
      postOptions: [],
      // 角色选项
      roleOptions: [],
      // 表单参数
      form: {},
      defaultProps: {
        children: 'children',
        label: 'label'
      },
      //文件信息列表
      fileInfoList:[],
      // 上传的文件列表
      fileList: [],
      // 用户导入参数
      upload: {
        // 是否显示弹出层（用户导入）
        open: false,
        // 弹出层标题（用户导入）
        title: '',
        // 是否禁用上传
        isUploading: false,
        // 是否更新已经存在的用户数据
        updateSupport: 0,
        // 设置上传的请求头部
        headers: { Authorization: 'Bearer ' + getToken() },
        // 上传的地址
        url: process.env.VUE_APP_BASE_API + '/excel/add',

      },
      filter:{
        // 是否显示弹出层（批量筛选）
        open:false,
        // 标题
        title:'批量筛选',
        numbers:[],
      },
      // 查询参数
      queryParams: {
        pageNum: 1,
        pageSize: 10,
        userName: undefined,
        phonenumber: undefined,
        status: undefined,
        deptId: undefined
      },
      // 列信息
      columns: [
        { key: 0, label: `文件名称`, visible: true },
        { key: 1, label: `文件大小`, visible: true },
        { key: 2, label: `是否已筛选`, visible: true },
        { key: 3, label: `创建时间`, visible: true }

      ],
      // 表单校验
      rules: {
        userName: [
          { required: true, message: '用户名称不能为空', trigger: 'blur' },
          { min: 2, max: 20, message: '用户名称长度必须介于 2 和 20 之间', trigger: 'blur' }
        ],
        nickName: [
          { required: true, message: '用户昵称不能为空', trigger: 'blur' }
        ],
        password: [
          { required: true, message: '用户密码不能为空', trigger: 'blur' },
          { min: 5, max: 20, message: '用户密码长度必须介于 5 和 20 之间', trigger: 'blur' }
        ]
      },
      dynamicValidateForm: {
        domains: [{
          value: ''
        }]
      }
    }
  },
  watch: {},
  created() {
    this.getList()
  },
  methods: {
    /** 查询用户列表 */
    getList() {
      this.loading = true
      this.loading = false
      getFileInfoList(this.queryParams).then(res=>{
        this.fileInfoList=res.rows
      })
    },
    // 取消按钮
    cancel() {
      this.open = false
      this.reset()
    },
    // 表单重置
    reset() {
      this.form = {
        userId: undefined,
        deptId: undefined,
        userName: undefined
      }
      this.resetForm('form')
    },
    /** 搜索按钮操作 */
    handleQuery() {
      this.queryParams.pageNum = 1
      this.getList()
    },
    /** 重置按钮操作 */
    resetQuery() {
      this.dateRange = []
      this.resetForm('queryForm')
      this.queryParams.deptId = undefined
      this.$refs.tree.setCurrentKey(null)
      this.handleQuery()
    },
    // 多选框选中数据
    handleSelectionChange(selection) {
      this.ids = selection.map(item => item.id)
      this.single = selection.length != 1
      this.multiple = !selection.length
    },
    // 更多操作触发
    handleCommand(command, row) {
      switch (command) {
        case 'handleResetPwd':
          this.handleResetPwd(row)
          break
        case 'handleAuthRole':
          this.handleAuthRole(row)
          break
        default:
          break
      }
    },
    /** 删除按钮操作 */
    handleDelete(row) {
      const ids = row.id || this.ids
      this.$modal.confirm('是否确认删除这' + ids.length + '条数据项？').then(function() {
        return delInfo(ids)
      }).then(res=> {
        this.getList()
        this.$modal.msgSuccess(res.msg)
      }).catch(() => {
      })
    },
    /** 导出按钮操作 */
    handleExport() {
      this.download('system/user/export', {
        ...this.queryParams
      }, `user_${new Date().getTime()}.xlsx`)
    },
    /** 导入按钮操作 */
    handleImport() {
      this.upload.title = '上传文件'
      this.upload.open = true
    },
    /** 下载模板操作 */
    importTemplate() {
      this.download('system/user/importTemplate', {}, `user_template_${new Date().getTime()}.xlsx`)
    },
    //文件状态改变处理
    handleFileChange(file,fileList){
      console.log("fileChange():"+fileList.length+"个文件")
    },
    //文件失败处理
    handleUploadError(err,file){
     console.log("文件上传失败："+JSON.stringify(err)+JSON.stringify(file))
      this.$message({
        message:"文件上传失败："+file.name+",请重新上传",
        type: 'error',
        showClose: true,
        duration: 0
      });
    },
    // 文件上传中处理
    handleFileUploadProgress(event, file, fileList) {
      this.upload.isUploading = true
    },
    // 文件上传成功处理
    handleFileSuccess(response, file, fileList) {
      let success=0
      this.$message({
        message: response.msg ,
        type: 'success',
      });
      fileList.forEach((item,index)=>{
        if(item.status==="success"){
          success++
        }
      })
      if(success===fileList.length){
        this.upload.open = false
        this.upload.isUploading = false
        this.$refs.upload.clearFiles()
        this.getList()
      }

    },

    // 提交上传文件
    submitFileForm() {
      this.$refs.upload.submit()
    },
    //批量筛选触发
    batchFilt(){
      if(this.ids.length===0){
        this.$alert("请选择文件")
      }else{
        this.filter.open=true;
      }
    },
    //筛选
    fileFilt(){
      let params={}
      params.fileIds=this.ids
      params.numbers=Array.from(this.dynamicValidateForm.domains,({value})=>value)
      filter(params)
      this.filter.open=false;
      this.getList()

    },
    //删除筛选条件
    removeDomain(item) {
      var index = this.dynamicValidateForm.domains.indexOf(item)
      if (index !== -1) {
        this.dynamicValidateForm.domains.splice(index, 1)
      }
    },
    // 新增筛选条件
    addDomain() {
      this.dynamicValidateForm.domains.push({
        value: '',
        key: Date.now()
      });
    },
    //导出筛选结果
    download(){
      this.$download.zip("/excel/download" , "filted.zip");
    }

}}
</script>
